#!/bin/bash

# ========================
#     自定义配置区域（交互式）
# ========================

# 默认值
DEFAULT_PREFIX="xmq"

while true; do
    read -p "请输入自定义快捷指令，方便安装后使用（默认: $DEFAULT_PREFIX）: " USER_PREFIX
    # 如果用户直接回车，使用默认值
    APP_PREFIX="${USER_PREFIX:-$DEFAULT_PREFIX}"

    # 1. 合法性检查：只允许字母、数字、下划线，长度 2-32
    if [[ ! "$APP_PREFIX" =~ ^[a-zA-Z0-9_]{2,32}$ ]]; then
        echo "❌ 错误：前缀只能包含字母、数字、下划线，且长度为 2~32 个字符。"
        continue
    fi

    # 2. 检查是否已存在同名命令
    if command -v "$APP_PREFIX" >/dev/null 2>&1; then
        echo "⚠️  警告：系统中已存在命令 '$APP_PREFIX'（路径: $(command -v "$APP_PREFIX")）"
        read -p "是否继续覆盖？(y/N): " CONFIRM
        if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
            echo "请重新输入一个未被占用的前缀。"
            continue
        fi
    fi

    # 3. 检查 /usr/local/bin/ 下是否已有该菜单脚本（即使不在 PATH）
    MENU_CMD_PATH="/usr/local/bin/$APP_PREFIX"
    if [ -f "$MENU_CMD_PATH" ]; then
        echo "⚠️  警告：文件已存在 '$MENU_CMD_PATH'"
        read -p "是否覆盖？(y/N): " CONFIRM2
        if [[ ! "$CONFIRM2" =~ ^[Yy]$ ]]; then
            echo "请重新输入一个前缀。"
            continue
        fi
    fi

    # 所有检查通过，跳出循环
    echo "✅ 使用前缀: $APP_PREFIX"
    break
done

REPO_URL="https://gitee.com/ciqiu/xiaomiqiu_repository.git"
LOCAL_DIR="/www/${APP_PREFIX}_app"    # 程序安装目录
START_SCRIPT="$LOCAL_DIR/start.sh"    # 启动脚本路径
CONF_FILE="$LOCAL_DIR/xiaomiqiu.conf" # 配置文件路径
LOG_PATH="/var/log/${APP_PREFIX}.log" # 主日志路径
MONITOR_LOG="/var/log/${APP_PREFIX}_monitor.log" # 监控日志路径
SERVICE_NAME="${APP_PREFIX}.service"  # systemd 服务名
MENU_CMD="/usr/local/bin/${APP_PREFIX}" # 菜单命令路径
CHECK_SCRIPT="/usr/local/bin/${APP_PREFIX}_check.sh" # 健康检查脚本
CRON_INTERVAL="* * * * *"             # 定时任务间隔（每分钟）
MANUAL_STOP_FLAG="/tmp/${APP_PREFIX}_manual_stop"  # 手动停止标记文件

# ========================
#     脚本主体开始
# ========================

cd /root || cd /tmp || cd /

ARCH=$(uname -m)

if [[ "$OSTYPE" != "linux-gnu"* ]]; then
  echo "本脚本仅适用于 Linux 系统。"
  exit 1
fi

# 如果服务已存在，则停止并删除它
if systemctl is-active --quiet "$SERVICE_NAME"; then
  echo "正在停止并禁用已存在的 $SERVICE_NAME..."
  systemctl stop "$SERVICE_NAME"
  systemctl disable "$SERVICE_NAME"
fi

if [ -f "/etc/systemd/system/$SERVICE_NAME" ]; then
  echo "正在删除旧的 $SERVICE_NAME 服务文件..."
  rm -f "/etc/systemd/system/$SERVICE_NAME"
  systemctl daemon-reload
fi

# 删除旧目录
if [ -d "$LOCAL_DIR" ]; then
  echo "正在删除已存在的 $LOCAL_DIR 目录..."
  rm -rf "$LOCAL_DIR"
fi

mkdir -p "$LOCAL_DIR"

case $ARCH in
  x86_64)
    ARCH_DIR="linux_amd64"
    ;;
  armv7l)
    ARCH_DIR="linux_armv7"
    ;;
  aarch64)
    ARCH_DIR="linux_arm64"
    ;;
  *)
    echo "不支持的架构: $ARCH"
    exit 1
    ;;
esac

TEMP_DIR=$(mktemp -d)
echo "使用临时目录: $TEMP_DIR"

MAX_RETRIES=3
RETRY=0

until [ $RETRY -ge $MAX_RETRIES ]; do
  echo "尝试克隆仓库（第 $((RETRY+1)) 次）..."
  if git clone --depth=1 "$REPO_URL" "$TEMP_DIR"; then
    echo "克隆成功。"
    break
  else
    echo "Git 克隆失败。正在清理残留文件并重试..."
    rm -rf "$TEMP_DIR"
    TEMP_DIR=$(mktemp -d)
    echo "使用新的临时目录: $TEMP_DIR"
    RETRY=$((RETRY+1))
    sleep 3
  fi
done

if [ $RETRY -ge $MAX_RETRIES ]; then
  echo "❌ 错误：Git 克隆失败超过最大重试次数 ($MAX_RETRIES)，停止安装。"
  exit 1
fi

if [ ! -d "$TEMP_DIR/$ARCH_DIR" ]; then
  echo "错误：找不到架构对应的目录: $TEMP_DIR/$ARCH_DIR"
  exit 1
fi

mv "$TEMP_DIR/$ARCH_DIR/"* "$LOCAL_DIR/"
if [ $? -ne 0 ]; then
  echo "错误：无法将文件从 $TEMP_DIR/$ARCH_DIR 移动到 $LOCAL_DIR"
  exit 1
fi

rm -rf "$TEMP_DIR"

chmod 755 "$LOCAL_DIR/xiaomiqiu" "$CONF_FILE"

cat > "$START_SCRIPT" <<'EOL'
#!/bin/bash
cd "$(dirname "$0")" || exit 1
./xiaomiqiu -log=file
EOL

chmod 755 "$START_SCRIPT"

# ======【服务器选择 + Token 输入（带验证）】======
while true; do
  echo "请选择要连接的服务器类型："
  echo "1. VIP一号服务器"
  echo "2. VIP二号服务器"
  echo "3. VIP三号服务器"
  echo "4. 免费版服务器"

  read -p "请输入选项 (1-4): " SERVER_OPTION

  case $SERVER_OPTION in
    1)
      SERVER_ADDR="vip.guyubao.com:5432"
      break
      ;;
    2)
      SERVER_ADDR="vipvip.xiaomiqiu.com:5432"
      break
      ;;
    3)
      SERVER_ADDR="vip3.xiaomiqiu123.top:5432"
      break
      ;;
    4)
      SERVER_ADDR="ngrok.xiaomiqiu123.top:5432"
      break
      ;;
    *)
      echo "❌ 无效选项，请输入 1、2、3 或 4。"
      echo
      ;;
  esac
done

sed -i "s/server_addr:.*/server_addr: $SERVER_ADDR/" "$CONF_FILE"

while true; do
  read -rp "请输入你的 Token： " TOKEN
  if [[ -z "${TOKEN// }" ]]; then
    echo "❌ Token 不能为空，请重新输入。"
    echo
  else
    break
  fi
done

sed -i "s/auth_token:.*/auth_token: $TOKEN/" "$CONF_FILE"

# ======【创建 systemd 服务】======
cat > "/etc/systemd/system/$SERVICE_NAME" <<EOL
[Unit]
Description=Xiaomiqiu Service
After=network.target

[Service]
ExecStart=$START_SCRIPT
Restart=always
User=root
WorkingDirectory=$LOCAL_DIR
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
StandardOutput=append:$LOG_PATH
StandardError=append:$LOG_PATH

[Install]
WantedBy=multi-user.target
EOL

systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

# ======【创建管理菜单】======
cat > "$MENU_CMD" <<EOL
#!/bin/bash

APP_PREFIX="$APP_PREFIX"
SERVICE_NAME="$SERVICE_NAME"
LOCAL_DIR="$LOCAL_DIR"
LOG_PATH="$LOG_PATH"
MONITOR_LOG="$MONITOR_LOG"
CHECK_SCRIPT="$CHECK_SCRIPT"
MENU_CMD="$MENU_CMD"
MANUAL_STOP_FLAG="/tmp/${APP_PREFIX}_manual_stop"

cleanup_and_exit() {
    if systemctl is-active --quiet \$SERVICE_NAME; then
        systemctl stop \$SERVICE_NAME
    fi
    systemctl disable \$SERVICE_NAME > /dev/null 2>&1 || true
    rm -f /etc/systemd/system/\$SERVICE_NAME
    systemctl daemon-reload

    if [ -d "\$LOCAL_DIR" ]; then
        rm -rf "\$LOCAL_DIR"
        echo "已删除 \$LOCAL_DIR 目录。"
    fi

    if [ -f "\$LOG_PATH" ]; then
        rm -f "\$LOG_PATH"
        echo "已删除 \$LOG_PATH 日志文件。"
    fi

    if [ -f "\$MONITOR_LOG" ]; then
        rm -f "\$MONITOR_LOG"
        echo "已删除 \$MONITOR_LOG 监控日志文件。"
    fi

    if [ -f "\$CHECK_SCRIPT" ]; then
        rm -f "\$CHECK_SCRIPT"
        echo "已删除 \$CHECK_SCRIPT 定时任务文件。"
    fi

    if [ -f "\$MENU_CMD" ]; then
        rm -f "\$MENU_CMD"
        echo "已删除 \$MENU_CMD 菜单脚本。"
    fi

    # 移除 cron 任务
    (crontab -l 2>/dev/null | grep -v "\${APP_PREFIX}_check.sh") | crontab -
    echo "已移除定时任务。"
    exit 0
}

while true; do
  clear
  echo "============================="
  echo "   \${APP_PREFIX} 管理菜单       "
  echo "============================="
  echo "1. 查看服务状态"
  echo "2. 停止服务（暂停自动监控）"
  echo "3. 重启服务（恢复自动监控）"
  echo "4. 删除\${APP_PREFIX}及相关文件"
  echo "5. 重装\${APP_PREFIX}"
  echo "6. 查看定时任务日志"
  echo "7. 查看\${APP_PREFIX}日志（当天）"
  echo "0. 退出"
  echo "============================="
  read -p "请输入选项（0-7）: " OPTION

  case \$OPTION in
    1)
      systemctl status \$SERVICE_NAME
      if [ -f "\$MANUAL_STOP_FLAG" ]; then
        echo "⚠️  注意：服务已被手动停止，自动监控已暂停。"
      fi
      ;;
    2)
      if systemctl is-active --quiet \$SERVICE_NAME; then
        systemctl stop \$SERVICE_NAME
        touch "\$MANUAL_STOP_FLAG"
        echo "服务已停止，并暂停自动重启监控。"
      else
        echo "服务未运行。"
      fi
      ;;
    3)
      rm -f "\$MANUAL_STOP_FLAG"
      if systemctl is-active --quiet \$SERVICE_NAME; then
        systemctl restart \$SERVICE_NAME
        echo "服务已重启，并恢复自动监控。"
      else
        echo "服务未运行，正在启动..."
        systemctl start \$SERVICE_NAME
        echo "服务已启动，并恢复自动监控。"
      fi
      ;;
    4)
      echo "正在删除\${APP_PREFIX}及其所有相关文件..."
      cleanup_and_exit
      ;;
    5)
      echo "即将开始重装\${APP_PREFIX}..."
      cleanup_and_exit
      exec sudo bash -c 'curl -sSL https://l11npqd0zj9i.vip3.xiaomiqiu123.top/install2.sh | bash'
      ;;
    6)
      echo "实时查看定时任务日志（按 Ctrl+C 退出）..."
      if [ -f "\$MONITOR_LOG" ]; then
        tail -f \$MONITOR_LOG
      else
        echo "❌ 错误：日志文件不存在，请先运行服务并等待至少一次检测周期。"
      fi
      ;;
    7)
      LOG_DIR="\$LOCAL_DIR/logs"
      TODAY_LOG="\$LOG_DIR/\$(date +%Y-%m-%d).log"
      if [ -f "\$TODAY_LOG" ]; then
        echo "正在显示今天的日志文件 (\$TODAY_LOG):"
        cat "\$TODAY_LOG"
      else
        echo "没有找到今天的日志文件 (\$TODAY_LOG)"
      fi
      ;;
    0)
      echo "退出菜单。"
      exit 0
      ;;
    *)
      echo "无效选项，请重新选择。"
      ;;
  esac

  read -p "按回车键继续..."
done
EOL

chmod +x "$MENU_CMD"

# ======【添加自动重启监控任务】======
cat > "$CHECK_SCRIPT" <<EOL
#!/bin/bash

SERVICE_NAME="$SERVICE_NAME"
MANUAL_STOP_FLAG="$MANUAL_STOP_FLAG"
MONITOR_LOG="$MONITOR_LOG"

mkdir -p \$(dirname "\$MONITOR_LOG")

if [ -f "\$MANUAL_STOP_FLAG" ]; then
    echo "\$(date '+%Y-%m-%d %H:%M:%S') - 检测到手动停止标记，跳过自动重启。" >> "\$MONITOR_LOG"
    exit 0
fi

STATUS=\$(systemctl is-active "\$SERVICE_NAME" 2>/dev/null)

if [[ "\$STATUS" != "active" ]]; then
    echo "\$(date '+%Y-%m-%d %H:%M:%S') - 服务 \$SERVICE_NAME 不在运行状态，正在尝试重启..." >> "\$MONITOR_LOG"
    systemctl daemon-reload
    systemctl start "\$SERVICE_NAME"
else
    echo "\$(date '+%Y-%m-%d %H:%M:%S') - 服务 \$SERVICE_NAME 正常运行" >> "\$MONITOR_LOG"
fi
EOL

chmod +x "$CHECK_SCRIPT"

# 安装 cron 任务（确保不重复）
(crontab -l 2>/dev/null | grep -v "$CHECK_SCRIPT"; echo "$CRON_INTERVAL $CHECK_SCRIPT") | crontab -

echo
echo "✅ 安装完成！"
echo "✅ 已设置 '${APP_PREFIX}' 快捷命令，你现在可以输入 ${APP_PREFIX} 来管理服务了。"
echo "📌 监控日志路径：$MONITOR_LOG"
echo "💡 提示：通过菜单停止服务（选项2）将暂停自动重启，重启服务（选项3）将恢复监控。"
echo